package com.yb.framework.fastdfs;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yb.common.constant.HttpStatusCode;

@RestController
@RequestMapping("/fastdfs")
public class FastDFSController {

	@Autowired
	private FastDFSClient fastDFSClient;
	
	@Value("${fdfs.serverIp}")
	private String serverIp;
	@Value("${fdfs.serverPort}")
	private String serverPort;
	
	private final Logger logger = LoggerFactory.getLogger(FastDFSController.class);
	
	@RequestMapping("/uploadFile")
	public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String filePath = fastDFSClient.uploadFile(file);
			result.put("filePath", "http://" + serverIp + ":" + serverPort + "/" + filePath);
			result.put("statusCode", HttpStatusCode.OK);
			result.put("message", "文件上传成功");
			return result;
		} catch (Exception e) {
			logger.error("文件上传失败", e);
			result.put("statusCode", HttpStatusCode.ERROR);
			result.put("message", "文件上传失败");
			return result;
		}
	}
	
	@RequestMapping("/downloadFile")
	public void downloadFile(@RequestParam("filePath") String filePath, HttpServletResponse response) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filePath, "UTF-8"));
			ServletOutputStream outputStream = response.getOutputStream();
			byte[] bytes = fastDFSClient.downloadFile(filePath);
			outputStream.write(bytes);
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			logger.error("文件下载失败", e);
		}
	}
	
	@RequestMapping("/deleteFile")
	public Map<String, Object> uploadFile(@RequestParam("filePath") String filePath) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			fastDFSClient.deleteFile(filePath);
			result.put("statusCode", HttpStatusCode.OK);
			result.put("message", "文件删除成功");
			return result;
		} catch (Exception e) {
			logger.error("文件删除失败", e);
			result.put("statusCode", HttpStatusCode.ERROR);
			result.put("message", "文件删除失败");
			return result;
		}
	}
}